import { defineConfig } from "vite";
import { fileURLToPath } from "node:url";
import uni from "@dcloudio/vite-plugin-uni";
import { execSync } from "node:child_process";
import path from "node:path";
import type { Plugin } from "vite";
// 自动打开 微信小程序 开发工具
function mpStart(): Plugin {
    let initialized = false;
    const openMp = () => {
        const __filename = fileURLToPath(import.meta.url);
        const __dirname = path.dirname(__filename);
        let mpPath = path.resolve(__dirname, "dist", "dev", "mp-weixin");
        let cli = "/Applications/wechatwebdevtools.app/Contents/MacOS/cli";
        execSync(`${cli} open --project ${mpPath}`, {
            stdio: "inherit",
            encoding: "utf-8",
        });
    };
    return {
        name: "vite-plugin-mp-go",
        apply: "build",
        writeBundle() {
            if (initialized) {
                return;
            }
            console.log("writeBundle  writeBundle", arguments.length);
            initialized = true;
            openMp();
        },
    };
}

// https://vitejs.dev/config/
export default defineConfig(function ({ mode, command, ssrBuild }) {
    let otherPlugins: Plugin[] = [];
    let { UNI_PLATFORM } = process.env || {};
    // dev 和 微信 添加 自动打开 小程序
    if (UNI_PLATFORM === "mp-weixin" && mode === "development") {
        otherPlugins.push(mpStart());
    }
    return {
        plugins: [uni(), ...otherPlugins],
        server: {
            open: true,
        },
    };
});
